import React from 'react';
import {
    Alert,
    Dimensions,
    FlatList,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View,
} from 'react-native';
import { check, openSettings, PERMISSIONS, request, RESULTS } from 'react-native-permissions';
import FastImage from '../../components/image/fast_image';
import PullToRefresh from '../../components/pull_to_refresh/refresh';

const { width } = Dimensions.get('window');

const itemWidth = (width - 16) / 2;

const secToTime = (s) => {
    let h = 0, m = 0;
    if (s > 60) {
        m = parseInt(s / 60);
        s = parseInt(s % 60);
        if (m > 60) {
            h = parseInt(i / 60);
            m = parseInt(i % 60);
        }
    }
    // 补零
    const zero = (v) => {
        return (v >> 0) < 10 ? ('0' + v) : v;
    };
    return (h == 0 ? [zero(m), zero(s)].join(':') : [zero(h), zero(m), zero(s)].join(':'));
};

export default class LivePage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
            data: [],
        };
    }

    componentWillUnmount(): void {
    }

    componentDidMount = () => {
        this.onRefreshing();
    };

    onRefreshing = () => {
        this.setState({
            refreshing: true,
        });

        setTimeout(() => {
            fetch('http://d.api.budejie.com/topic/list/jingxuan/41/bs0315-android-4.5.9/0-20.json').then((response) => response.json())
                .then((jsonData) => {
                    this.setState({
                        refreshing: false,
                        data: jsonData.list.slice(),
                        np: jsonData.info.np || 0,
                    });
                });
        }, 300);
    };

    _onEndReached = () => {
        fetch(`http://d.api.budejie.com/topic/list/jingxuan/41/bs0315-android-4.5.9/${this.state.np}-20.json`)
            .then((response) => response.json())
            .then((jsonData) => {
                this.setState({
                    data: [...this.state.data, ...jsonData.list],
                    np: jsonData.info.np,
                });
            });
    };

    _keyExtractor = (item, index) => {
        return item.text + index;
    };

    _renderItem = ({ item }) => {
        return (
            <TouchableOpacity
                activeOpacity={0.75}
                onPress={() => this._goToPlayerRoom(item)}
                style={styles.item}>
                <FastImage
                    source={{ uri: item.video.thumbnail[0] }}
                    style={{ width: itemWidth, height: 180, borderRadius: 4 }}
                />
                <View style={styles.itemText}>
                    <Text style={{ color: '#fff' }}>{secToTime(item.video.duration)}</Text>
                    <Text style={{ color: '#fff' }}>{item.comment}</Text>
                </View>
            </TouchableOpacity>
        );
    };

    _goToPlayerRoom = (item) => {
        this.props.navigation.navigate('liveRoom', { streamUrl: item.video.video[0] });
    };

    _checkPermissionsAndForward = () => {
        const isAndroid = Platform.OS === 'android';
        Promise
            .all(
                isAndroid ? [
                    check(PERMISSIONS.ANDROID.CAMERA),
                    check(PERMISSIONS.ANDROID.RECORD_AUDIO),
                ] : [
                    check(PERMISSIONS.IOS.CAMERA),
                    check(PERMISSIONS.IOS.MICROPHONE),
                ],
            )
            .then(async ([cameraStatus, audioStatus]) => {
                // 判断摄像头
                switch (cameraStatus) {
                    // 服务不可用
                    case RESULTS.UNAVAILABLE:
                        Alert.alert(
                            '',
                            '您当前设备相机服务不可用，功能无法正常使用',
                            [
                                { text: '我知道了' },
                            ],
                            { cancelable: false },
                        );
                        return false;
                    // 可以申请授权
                    case RESULTS.DENIED:
                        const requestCameraStatus = await request(isAndroid ? PERMISSIONS.ANDROID.CAMERA : PERMISSIONS.IOS.CAMERA);
                        if (requestCameraStatus !== RESULTS.GRANTED) {
                            Alert.alert(
                                '',
                                '您尚未开启拍摄权限，功能无法正常使用',
                                [
                                    { text: '我知道了' },
                                    {
                                        text: '开启权限',
                                        onPress: () => {
                                            openSettings().catch(() => console.warn('cannot open settings'));
                                        },
                                    },
                                ],
                                { cancelable: false },
                            );
                            return;
                        }
                        break;
                    // 该权限被拒绝，不再需要
                    case RESULTS.BLOCKED:
                        Alert.alert(
                            '',
                            '您尚未开启拍摄权限，功能无法正常使用',
                            [
                                { text: '我知道了' },
                                {
                                    text: '开启权限',
                                    onPress: () => {
                                        openSettings().catch(() => console.warn('cannot open settings'));
                                    },
                                },
                            ],
                            { cancelable: false },
                        );
                        return false;
                }

                // 判断录音
                switch (audioStatus) {
                    // 服务不可用
                    case RESULTS.UNAVAILABLE:
                        Alert.alert(
                            '',
                            '您当前设备麦克风服务不可用，功能无法正常使用',
                            [
                                { text: '我知道了' },
                            ],
                            { cancelable: false },
                        );
                        return false;

                    // 可以申请授权
                    case RESULTS.DENIED:
                        const requestAudioStatus = await request(isAndroid ? PERMISSIONS.ANDROID.RECORD_AUDIO : PERMISSIONS.IOS.MICROPHONE);
                        if (requestAudioStatus !== RESULTS.GRANTED) {
                            Alert.alert(
                                '',
                                '您尚未开启麦克风权限，功能无法正常使用',
                                [
                                    { text: '我知道了' },
                                    {
                                        text: '开启权限',
                                        onPress: () => {
                                            openSettings().catch(() => console.log('cannot open settings'));
                                        },
                                    },
                                ],
                                { cancelable: false },
                            );
                            return;
                        }
                        break;

                    // 该权限被拒绝，不再需要
                    case RESULTS.BLOCKED:
                        Alert.alert(
                            '',
                            '您尚未开启麦克风权限，功能无法正常使用',
                            [
                                { text: '我知道了' },
                                {
                                    text: '开启权限',
                                    onPress: () => {
                                        openSettings().catch(() => console.log('cannot open settings'));
                                    },
                                },
                            ],
                            { cancelable: false },
                        );
                        return;
                }

                this.props.navigation.navigate('streamRoom');
            });
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    animated={false}
                    backgroundColor={'#000000'}
                    barStyle={'light-content'}
                />
                <PullToRefresh style={{ flex: 1 }}>
                    <FlatList
                        data={this.state.data}
                        numColumns={2}
                        renderItem={this._renderItem}
                        keyExtractor={this._keyExtractor}
                        getItemLayout={(data, index) => (
                            { length: 188, offset: 188 * index, index }
                        )}
                    />
                </PullToRefresh>
                <TouchableWithoutFeedback
                    onPress={this._checkPermissionsAndForward}
                >
                    <View style={styles.floatingButton}>
                        <Text>直播</Text>
                    </View>
                </TouchableWithoutFeedback>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#000000',
    },
    item: {
        margin: 4,
    },
    itemText: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 10,
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        height: 30,
        backgroundColor: '#0002',
        borderBottomLeftRadius: 4,
        borderBottomRightRadius: 4,
    },
    floatingButton: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        position: 'absolute',
        bottom: 55,
        right: 25,
        width: 56,
        height: 56,
        borderRadius: 28,
        zIndex: 10,
        backgroundColor: '#fff',
    },
});
